<template>
	<view class="page container">
		<u-form :model="basicForm" :rules="rules" labelPosition="top" ref="form" labelWidth="auto" :labelStyle="{
        fontSize: '14px',
        color: '#B2B2B2',
        lineHight: '20px',
      }">
			<view class="basic-style">
				<u-form-item label="关联借款申请" prop="loanBillId" required>
					<h-select-borrowbill-input-popup :checkStatus="2" :teamId="teamId" :companyId="companyId"
						:settleAccounts="0" :proposer="proposer" class="w-100" v-model="basicForm.loanBillId"
						placeholder="请选择关联借款申请" border="surround" suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
						@realChange="handleLoanBillChange"></h-select-borrowbill-input-popup>
				</u-form-item>
				<u-form-item label="借款金额（元）" prop="amount">
					<u--input disabled v-model="basicForm.amount" v-number-normal placeholder="请输入借款金额"></u--input>
				</u-form-item>
				<u-form-item label="使用日期" prop="useDate">
					<h-time-select disabled mode="datetime" ref="useDate" v-model="basicForm.useDate"
						placeholder="请选择使用日期" border="surround" suffixIcon="calendar-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }" @change="handleTimeChange"></h-time-select>
				</u-form-item>
				<u-form-item label="归还日期" prop="returnDate">
					<h-time-select disabled ref="returnDate" mode="datetime" v-model="basicForm.returnDate"
						placeholder="请选择归还日期" border="surround" suffixIcon="calendar-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }" @change="handleTimeChange"></h-time-select>
				</u-form-item>
				<u-form-item label="本次还款金额（元）" prop="currentReturnAmount" required>
					<h-money-input placeholder="请输入本次还款金额" v-model="basicForm.currentReturnAmount"></h-money-input>
					<!-- <u--input v-model="basicForm.currentReturnAmount" :min="0" :max="99999999" placeholder="请输入本次还款金额"></u--input> -->
				</u-form-item>
				<u-form-item label="累计已还金额（元）" prop="returnedTotalAmount">
					<u--input disabled type="number" v-number-normal placeholder="请输入累计已还金额"
						v-model="basicForm.returnedTotalAmount"></u--input>
				</u-form-item>
				<u-form-item label="累计已报销金额（元）" prop="reimbursedTotalAmount">
					<u--input disabled type="number" v-number-normal placeholder="请输入累计已报销金额"
						v-model="basicForm.reimbursedTotalAmount"></u--input>
				</u-form-item>
				<u-form-item label="总冲账金额（元）" prop="totalAmount">
					<u--input disabled type="number" v-number-normal placeholder="请输入总冲账金额"
						v-model="basicForm.totalAmount"></u--input>
				</u-form-item>
				<u-form-item label="剩余未还金额（元）" prop="unreturnedTotalAmount">
					<u--input disabled type="number" v-number-normal placeholder="请输入剩余未还金额"
						v-model="basicForm.unreturnedTotalAmount"></u--input>
				</u-form-item>

				<u-form-item label="备注" prop="remark">
					<u--textarea v-model="basicForm.remark" :confirm-type="null" maxlength="500" count
						placeholder="请输入备注" :cursorSpacing="100"></u--textarea>
				</u-form-item>
			</view>

			<view class="space-x-1 mt-1" style="display: flex">
				<u-button type="primary" text="保存" :loading="loading" @click="onSubmit"></u-button>
				<u-button type="primary" text="关闭" :loading="loading" @click="onClose"></u-button>
			</view>
		</u-form>
	</view>
</template>

<script>
	import {
		Decimal
	} from 'decimal.js'
	import moment from 'moment'

	export default {
		name: 'SplitForm',
		props: {
			teamId: {
				type: [String, Number],
				default: '',
			},
			companyId: {
				type: [String, Number],
				default: '',
			},
			// 表单禁用
			disabled: {
				type: Boolean,
				default: false,
				required: false,
			},
			isRelProject: {
				type: Boolean,
				default: false,
			},
			datailDisabled: {
				type: Boolean,
				default: false,
			},
			index: {
				type: Number,
				default: null,
			},
			formType: {
				type: String,
				default: 'trip',
			},
		},
		data() {
			return {
				loading: false,
				proposer: uni.getStorageSync('userInfo').empId,
				basicForm: {
					loanBillId: '',
					amount: '',
					useDate: '',
					returnDate: '',
					currentReturnAmount: '',
					returnedTotalAmount: '',
					reimbursedTotalAmount: '',
					totalAmount: '',
					unreturnedTotalAmount: '',
					remark: '',
				},
				rules: {
					currentReturnAmount: [{
							required: true,
							message: '请输入本次还款金额!',
							trigger: 'blur'
						},
						{
							pattern: /^(?!0\.00)(?!0$)([1-9]\d*|0)(\.\d{2})?$/,
							message: '请输入正确的还款金额!'
						},
					],
					loanBillId: [{
						required: true,
						message: '请选择关联借款单!',
						trigger: 'change'
					}],
				},
			}
		},
		created() {},
		methods: {
			/**
			 * 选择关联借款单申请
			 */
			handleLoanBillChange(res) {
				if (res) {
					this.$set(this.basicForm, 'amount', res.amount)
					this.$set(this.basicForm, 'useDate', res.useDate)
					this.$set(this.basicForm, 'returnDate', res.returnDate)
					this.$set(this.basicForm, 'returnedTotalAmount', res.repaymentAmount)
					this.$set(this.basicForm, 'reimbursedTotalAmount', res.travelReimbursementAmount + res
						.expenseReimbursementAmount)
					this.$set(this.basicForm, 'totalAmount', res.repaymentAmount + res.travelReimbursementAmount + res
						.expenseReimbursementAmount)
					let amount = new Decimal(this.basicForm.amount).sub(new Decimal(this.basicForm.totalAmount))
					this.$set(this.basicForm, 'unreturnedTotalAmount', amount.toNumber().toFixed(2))
				} else {
					this.$set(this.basicForm, 'amount', '')
					this.$set(this.basicForm, 'useDate', '')
					this.$set(this.basicForm, 'returnDate', '')
					this.$set(this.basicForm, 'returnedTotalAmount', '')
					this.$set(this.basicForm, 'reimbursedTotalAmount', '')
					this.$set(this.basicForm, 'totalAmount', '')
					this.$set(this.basicForm, 'unreturnedTotalAmount', '')
				}
			},
			reset() {
				this.$refs.form.resetFields()
			},
			handleMileageChange() {
				const {
					startMileage,
					endMileage,
					subsidyUnitPrice
				} = this.basicForm
				if ((startMileage || startMileage === 0) && (endMileage || endMileage === 0)) {
					mileage = endMileage - startMileage
					let mileage = new Decimal(endMileage).sub(new Decimal(startMileage))
					this.basicForm.mileage = mileage.toNumber().toFixed(2)
				}
				if (subsidyUnitPrice) {
					this.subsidyUnitPriceInput(subsidyUnitPrice)
				}
			},
			subsidyUnitPriceInput(data) {
				let price = 1
				if (data == 1) {
					price = 1
				} else if (data == 2) {
					price = 1.5
				}
				if (
					(this.basicForm.startMileage || this.basicForm.startMileage == 0) &&
					(this.basicForm.endMileage || this.basicForm.endMileage == 0)
				) {
					this.basicForm.amount = price * this.basicForm.mileage
				}
			},
			getDaysBetween(date1, date2) {
				const startDate = Date.parse(date1)
				const endDate = Date.parse(date2)
				const date3 = endDate - startDate //时间差的毫秒数
				//计算出相差天数
				const days = Math.floor(date3 / (24 * 3600 * 1000))
				//计算出小时数
				const leave1 = date3 % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
				const hours = Math.floor(leave1 / (3600 * 1000))

				const dayHours = days + '天' + hours + '小时'
				return dayHours
			},
			handleTimeChange() {
				const {
					useDate,
					returnDate
				} = this.basicForm
				if (useDate && returnDate) {
					if (moment(returnDate).diff(moment(useDate), 'seconds') < 0) {
						this.basicForm.returnDate = useDate
						this.$refs.returnDate.valueName = useDate
						this.$u.toast('回程时间不得小于出发时间')
						this.basicForm.days = this.getDaysBetween(useDate, useDate)
						return
					}
					this.basicForm.days = this.getDaysBetween(useDate, returnDate)
				}
			},
			handleAmountChange() {
				if ((this.basicForm.amount || this.basicForm.amount === 0) && (this.basicForm.taxation || this.basicForm
						.taxation === 0)) {
					let money = new Decimal(this.basicForm.amount).sub(new Decimal(this.basicForm.taxation))
					this.basicForm.untaxedAmount = money.toNumber().toFixed(2)
				}
			},
			// async onSubmit() {
			//   await this.$refs.form.validate()
			//   this.$emit('submit', [this.basicForm, this.index])
			//   this.reset()
			// },
			async onSubmit() {
				await this.$refs.form.validate().then(async () => {
					if (this.basicForm.currentReturnAmount > this.basicForm.unreturnedTotalAmount) {
						this.$u.toast('本次还款金额大于剩余未还金额，请重新输入！')
						return Promise.reject('本次还款金额大于剩余未还金额，请重新输入！')
					}
				})
				if (!this.index) {
					this.$emit('submit', [{
							id: parseInt(Math.random() * 1000000000000),
							...this.basicForm,
						},
						this.index,
					])
				} else {
					this.$emit('submit', [this.basicForm, this.index])
				}
				this.reset()
			},
			handleProjectSelect({
				data
			}) {
				this.basicForm.taskId = ''
				this.basicForm.taskDescription = ''
				this.basicForm.attributionYear = data?.year || ''
			},
			onClose() {
				this.$emit('close')
				this.reset()
			},
		},
		watch: {
			isRelProject(val) {
				if (val === '1') {
					this.$set(this.rules, 'projectId', [{
						required: true,
						message: '请选择关联项目!',
						trigger: 'change'
					}])
					this.$set(this.rules, 'taskId', [{
						required: true,
						message: '请选择任务分类!',
						trigger: 'change'
					}])
				} else {
					this.$set(this.rules, 'projectId', [])
					this.$set(this.rules, 'taskId', [])
				}
			}
		},
	}
</script>

<style scoped>
	@import url('@/assets/inputStyle.scss');

	.page.container {
		padding: 20px;
	}

	.basic-style {
		margin: 0;
		max-height: 80vh;
		overflow-y: auto;
	}

	.u-form-item {
		padding: 0px 8px;
	}
</style>